package edu.xidian.onlinedocument.utils.ot.json;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import edu.xidian.onlinedocument.utils.ot.internal.operations.Change;
import edu.xidian.onlinedocument.utils.ot.internal.operations.ChangesList;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * 传参对象：WebSocket连接的服务端
 * 传参内容：本地存储的用户账号userNum以及数据结构ChangesList
 * 返回对象：WebSocket连接的客户端
 * 返回内容：由userNum和ChangesList经过包装得到的JSON格式数据
 */
public class ToJSON {
    private ToJSON() {}

    public static List<JSONObject> fromChangesListToJSON(String userNum, List<ChangesList> changesList) {
        List<JSONObject> object = new ArrayList<>();
        for (ChangesList c:
             changesList) {
            object.add(ToJSON.fromChangesListToJSON(userNum, c));
        }
        return object;
    }

    public static JSONObject fromChangesListToJSON(String userNum, ChangesList changesList) {
        ChangesListJSON data = fromChangesListToChangesData(userNum, changesList);

        JSONObject object = JSONObject.parseObject(JSON.toJSONString(data));

        /*
        System.out.println("-----fromChangesListToJSON-----");
        System.out.println("-----from ChangesList-----");
        System.out.println(changesList);
        System.out.println("-----to JSON-----");
        System.out.println(object);
         */

        return object;
    }

    private static ChangesListJSON fromChangesListToChangesData(String userNum, ChangesList list) {
        ChangesListJSON data = new ChangesListJSON(userNum, list.getRevision(), new LinkedList<>());

        List<Change> changes = list.getChanges();

        for (Change c:
             changes) {
            String opName = OperationClass.OprationName(c.getClass());
            if(StringUtils.isNoneBlank(opName)) {
                ChangeJSON d = new ChangeJSON(opName, c.offset(), c.value());
                data.getChangeList().add(d);
            }
        }
        return data;
    }
}
